import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:yp/config/style.dart';
import 'package:yp/widgets/cache_image.dart';

class AdBox extends StatefulWidget {
  /// 广告位的Key
  final String adKey;

  final Map<String, dynamic> args;

  List imageList = [
    {'id': '0', 'logo': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0120b35e251437a801216518060488.jpg%402o.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634227251&t=83bffff0b3d4759c0153b9d7cb096f7e'},
    {'id': '1', 'logo': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.o431.cn%2Fnews%2FUploadFiles%2F201912%2F2019120314411539.jpg&refer=http%3A%2F%2Fwww.o431.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634228562&t=b5383f096e972a924fedab439394a20c'},
    {'id': '2', 'logo': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.16pic.com%2F00%2F11%2F23%2F16pic_1123089_b.jpg&refer=http%3A%2F%2Fpic.16pic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634227251&t=fe436dcbeb5bc9afbb1e700da1e3102e'},
    {'id': '3', 'logo': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.sccnn.com%2Fbimg%2F341%2F04572.jpg&refer=http%3A%2F%2Fimg.sccnn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634227251&t=3ecf54c2b5d2a778b8455226c330fd1d'}
  ];

  /// 如果轮播的话。是否中间放大
  final bool enlargeCenterPage;

  /// 占位高度
  final double height;

  /// 图片圆角
  final double borderRadius;

  final EdgeInsetsGeometry margin;

  final double aspectRatio;

  ///是否展示阴影
  final bool displayShadow;

  final Function adExistCallBack;

  AdBox({Key key, @required this.adKey, this.borderRadius = 0, this.enlargeCenterPage = false, this.displayShadow = false, this.height = 100, this.aspectRatio, this.margin = const EdgeInsets.all(0), this.adExistCallBack, this.args, bool text})
      : assert(adKey != null),
        assert(height != null),
        assert(aspectRatio != null);

  @override
  _AdBoxState createState() => _AdBoxState();
}

class _AdBoxState extends State<AdBox> {
  var _advList;
  var _adv;

  /// 是否多张图片(true:轮播，false:单张)
  bool isMultiple;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _advList = widget.imageList;
    print('widget.imageList');
    print(widget.imageList);
    if (widget.imageList.length == 1) {
      _adv = widget.imageList[0];
    }

    isMultiple = _advList.length != 1;
    return isMultiple ? buildMutiple() : buildSingle();
  }

  void itemTap(var item) {
    print(item);
  }

  // 单张
  Widget buildSingle() {
    return GestureDetector(
      onTap: () {
        itemTap(_adv);
      },
      child: AspectRatio(
        aspectRatio: widget.aspectRatio,
        child: CachedImage(
          margin: widget.margin,
          width: double.infinity,
          height: widget.height,
          borderRadius: widget.borderRadius,
          path: _adv['logo'] ?? '',
          bgColor: EsColors.White,
          scale: BoxFit.fill,
          shadows: widget.displayShadow
              ? [
                  BoxShadow(
                    color: Color(0xFF4758BF).withOpacity(0.12),
                    blurRadius: 6,
                    spreadRadius: 1,
                  )
                ]
              : [],
        ),
      ),
    );
  }

  // 轮播
  Widget buildMutiple() {
    return AspectRatio(
      aspectRatio: widget.aspectRatio,
      child: Swiper(
        key: GlobalKey(),
        containerHeight: widget.height,
        containerWidth: double.infinity,
        loop: true,
        autoplay: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              itemTap(_advList[index]);
            },
            child: CachedImage(
              margin: widget.margin,
              height: widget.height,
              borderRadius: widget.borderRadius,
              path: _advList[index]['logo'],
              bgColor: EsColors.White,
              scale: BoxFit.fill,
              shadows: widget.displayShadow
                  ? [
                      BoxShadow(
                        color: Color(0xFF4758BF).withOpacity(0.12),
                        blurRadius: 8.0,
                        spreadRadius: 1.0,
                      )
                    ]
                  : [],
            ),
          );
        },
        itemCount: _advList?.length ?? 0,
        scrollDirection: Axis.horizontal,
        pagination: SwiperPagination(
            margin: EdgeInsets.only(bottom: 0),
            builder: SwiperPagination(builder: SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
              return EsIndicator(config.activeIndex, _advList.length);
            }))),
      ),
    );
  }
}

class EsIndicator extends StatelessWidget {
  final int currentIndex;
  final int count;

  EsIndicator(this.currentIndex, this.count);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(count, (index) {
        return currentIndex == index
            ? Container(
                width: 16,
                height: 6,
                margin: EdgeInsets.only(right: 6),
                decoration: BoxDecoration(color: EsColors.Primary, borderRadius: BorderRadius.circular(6)),
              )
            : Container(
                width: 6,
                height: 6,
                margin: EdgeInsets.only(right: 4),
                decoration: BoxDecoration(color: EsColors.Fill, borderRadius: BorderRadius.circular(6)),
              );
      }),
    );
  }
}
